package com.zkzx.util.ftp.utils;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.AllArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
@AllArgsConstructor
public class OssObjectUtils {

    @Setter
    private String bucketName;
    @Setter
    private String endpoint;
    @Setter
    private String accessKeyId;
    @Setter
    private String accessKeySecret;
    @Setter
    private String ossAccountName;

    OSS ossClient;

    //TODO 上传图片 需要配置

    public OssObjectUtils(String bucketName, String endpoint, String accessKeyId, String accessKeySecret, String ossAccountName) {
        this.bucketName = bucketName;
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.ossAccountName = ossAccountName;
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 无参构造,设置默认值
     */
    public OssObjectUtils() {
        this.bucketName = "datahub-external-upload";
        this.endpoint = "oss-cn-hangzhou.aliyuncs.com";
        this.accessKeyId = "LTAI4GJCzdd7mEh7sg6f16VW";
        this.accessKeySecret = "ixIpiUPiaAHgmxMkD2kXle8DJ0gyt2";
        this.ossAccountName = "OSSSJSNSJLR20190208/";
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }


    /**
     * @param localPath  本地地址  路径+文件名+扩展名
     * @param targetPath 目标地址 oss上文件全路径+扩展名
     * @return 是否上传成功
     */
    public boolean uploadFile(String localPath, String targetPath) {
        boolean uploadResult;
        try {
            PutObjectResult result = ossClient.putObject(bucketName, ossAccountName + targetPath, readToBytes(localPath));
            log.info("上传文件{}，结果为：{}", targetPath, JSON.toJSONString(result));
            uploadResult = true;
        } catch (Exception e) {
            log.info("uploadFile 异常", e.fillInStackTrace());
            uploadResult = false;
        }
        /*finally {
            if (null != ossClient) {
                ossClient.shutdown();
            }
        }*/
        return uploadResult;
    }

    public void shutdown(){
        ossClient.shutdown();
    }

    /**
     * oss删除单个文件
     *
     * @param fileFullPath oss上文件全路径+扩展名
     */
    public boolean deleteFile(String fileFullPath) {
        boolean result;
        try {
            ossClient.deleteObject(bucketName, ossAccountName + fileFullPath);
            result = true;
        } catch (Exception e) {
            log.error("删除异常,fileFullPath:".concat(fileFullPath), e.fillInStackTrace());
            result = false;
        }
        /*finally {
            ossClient.shutdown();
        }*/
        return result;
    }

    /**
     * 判断对象是否存在
     *
     * @param fileFullPath
     * @return
     */
    public boolean judgeFile(String fileFullPath) {
        boolean isExist = false;
        try {
            isExist = ossClient.doesObjectExist(bucketName, ossAccountName + fileFullPath);
        } catch (Exception e) {
            log.error("judgeFile异常,fileFullPath:".concat(fileFullPath), e.fillInStackTrace());
        }
        /*finally {
            ossClient.shutdown();
        }*/
        return isExist;
    }


    /**
     * 下载文件
     * fileFullPath oss上文件全路径+扩展名
     * filePath	本地文件存放地址（包含文件名）
     */
    public boolean getFile(String fileFullPath, String localFilePath) {
        boolean result;
        try {
            ossClient.getObject(new GetObjectRequest(bucketName, ossAccountName + fileFullPath), new File(localFilePath));
            result = true;
        } catch (Exception e) {
            log.error("getFile失败,fileFullPath:".concat(fileFullPath), e.fillInStackTrace());
            result = false;
        }
        /*finally {
            ossClient.shutdown();
        }*/
        return result;
    }

    public static ByteArrayInputStream readToBytes(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        long filelength = file.length();
        byte[] filecontent = new byte[(int) filelength];
        try (FileInputStream in = new FileInputStream(file)) {
            int readSize = in.read(filecontent);
        } catch (IOException e) {
            log.error("FileInputStream 异常： " + encoding, e.fillInStackTrace());
        }
        try {
            return new ByteArrayInputStream(filecontent);
        } catch (Exception e) {
            log.error("ByteArrayInputStream 异常：" + encoding, e.fillInStackTrace());
            return null;
        }
    }
}




